<template>
  <div class="update-name">
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="确定"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        placeholder="请输入昵称"
        maxlength="7"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from "@/api/user";
export default {
  name: "UpdateName",
  props: {
    value: {
      type: String,
      require: true,
    },
  },
  data() {
    return {
      localName: this.value,
    };
  },
  methods: {
    async onConfirm() {
      // 昵称未变更，直接关闭弹层
      if(this.localName === this.value) {
        this.$emit("close");
        return
      }
      // loading加载效果
      this.$toast.loading({
        message: "保存中...",
        forbidClick: false,
        duration: 0,
      });
      try {
        if (!this.localName.length) {
          this.$toast.fail("昵称不能为空");
          return;
        }
        await updateUserProfile({
          name: this.localName,
        });
        this.$toast.success("更新成功");
        this.$emit("input", this.localName);
        this.$emit("close");
      } catch (err) {
        // 优化409报错提示信息
        if (err.response && err.response.status === 409) {
          this.$toast.fail("用户名已存在");
        } else {
          this.$toast.fail("更新失败");
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
.field-wrap {
  padding: 20px;
}
</style>